package jianzhiOffer;

/**
 * 反转链表
 */
public class T00024 {

    public static void main(String[] args) {
        ListNode node = build(1,2);
        print(node);
        print(new Solution().reverseList(node));
    }

    static void print(ListNode node) {
        if(node == null)
            return;
        ListNode c = node;
        for(;;) {
            System.out.print(c.val);
            if((c = c.next) == null)
                break;
            System.out.print(" -> ");
        }
        System.out.println();
    }

    static ListNode build(int... arr) {
        if(arr == null || arr.length == 0)
            return null;
        ListNode p = null;
        for (int i = arr.length - 1; i >= 0; i --) {
            ListNode t = new ListNode(arr[i]);
            t.next = p;
            p = t;
        }
        return p;
    }

static class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode next = head.next;
        do {
            ListNode t = head;
            head = next;
            next = head.next;
            head.next = t;
            if(t.next == head)
                t.next = null;
        } while(next != null);
        return head;
    }
}

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}
